package com.fc.test.controller.admin;

import java.io.*;
import java.net.InetAddress;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fc.test.common.conf.V2Config;
import com.fc.test.common.file.FileUploadUtils;
import com.fc.test.common.file.FileUtils;
import com.fc.test.controller.HomeController;
import com.fc.test.util.CustomSystemUtil;
import com.fc.test.util.DateUtil;
import com.fc.test.util.HttpUtil;
import com.fc.test.util.SnowflakeIdWorker;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.fc.test.common.base.BaseController;
import com.fc.test.common.domain.AjaxResult;
import com.fc.test.model.auto.TsysDatas;
import com.fc.test.model.auto.TsysFile;
import com.fc.test.model.custom.TableSplitResult;
import com.fc.test.model.custom.Tablepar;
import com.fc.test.model.custom.TitleVo;
import com.github.pagehelper.PageInfo;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件上传controller
 * @author fuce
 * @date: 2018年9月16日 下午4:23:50
 */
@Controller
@Api(value = "文件上传",tags={"文件操作接口"})
@RequestMapping("FileController")
public class FileController extends BaseController{
	private static Logger logger= LoggerFactory.getLogger(HomeController.class);
	//跳转页面参数
	private String prefix = "admin/file";


	@GetMapping("view")
	@RequiresPermissions("system:file:view")
    public String view(Model model)
    {

		setTitle(model, new TitleVo("上传图片列表", "图片管理", false,"欢迎进入图片页面", false, false));
        return prefix + "/list";
    }

	/**
	 * 文件列表
	 * @param tablepar
	 * @param searchTxt 搜索字符
	 * @return
	 */
	@PostMapping("list")
	@RequiresPermissions("system:file:list")
	@ResponseBody
	public Object list(Tablepar tablepar,String searchTxt){
		PageInfo<TsysFile> page=sysFileService.list(tablepar,searchTxt) ;
		TableSplitResult<TsysFile> result=new TableSplitResult<TsysFile>(page.getPageNum(), page.getTotal(), page.getList());
		return  result;
	}

	/**
     * 新增文件
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

	/**
	 * 多文件上传到服务器路径
	 * @param myfiles
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
	@ResponseBody
	public  List<Map<String,String>> upload(@RequestParam MultipartFile[] myfiles, String param, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException{
		logger.info("Entering upload previewId={}",param);
		String day=DateUtil.getCurrentDay();
		//获取当前用户
		String realPath = request.getSession().getServletContext().getRealPath(File.separator+"upload"+File.separator+day);
		File file = new File(realPath);
		if (!file.exists()) {//文件夹不存在 创建文件夹
			file.mkdirs();
		}
		response.setContentType("text/plain; charset=UTF-8");
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		String originalFilename = null;
		for(MultipartFile myfile : myfiles){
			Map<String,String> map = new HashMap<String,String>();
			if(myfile.isEmpty()){
				logger.info("请选择文件后上传!");
				return null;
			}else{
				originalFilename = myfile.getOriginalFilename();
				String extension =FilenameUtils.getExtension(originalFilename);
				if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)){
					originalFilename=System.currentTimeMillis()+"."+ FilenameUtils.getExtension(originalFilename);
					try {
						myfile.transferTo(new File(realPath, originalFilename));
						//保存文件路径
						//creditFileService.insertFile(File.separator+"upload"+File.separator+day+File.separator+originalFilename, companyId, creditId);
						map.put("pathUrl","/upload/"+day+"/"+originalFilename);
						list.add(map);
						logger.info("load success " + request.getContextPath()+File.separator+"upload"+File.separator+day+File.separator+originalFilename);
						logger.info("leaving upload!");
					}catch (Exception e) {
						logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
						e.printStackTrace();
						logger.info("文件上传失败，请重试！！");
						return null;
					}
				}else{
					logger.info("load success 只支持jpg,png格式");
				}
			}
		}
		return list;
	}


	 /**
     * 多文件或者单文件上传到磁盘路径下
     * */
   @RequestMapping(value = "/uploadReport", method = RequestMethod.POST)
	  public void uploadReport(HttpServletRequest request, HttpServletResponse response,String reportGroupId) {
		   Map<String, Object> result = new HashMap<String, Object>();
		 //调用通用接口上传文件
		   result = uploadFile(request, "reportFile", reportGroupId);
		  HttpUtil.formatResponse(response, result);
   }
	/**
	 * 上传文件通用接口
	 *
	 * @param request           请求体
	 * @param dstFileName       html上传组件中(input中name属性)，上传文件体名称，通过此名称获取所有上传的文件map
	 * @param reportGroupId     （特殊）上传报告所述报告组id
	 * */
	protected Map<String, Object> uploadFile(HttpServletRequest request, String dstFileName, String reportGroupId) {
		Map<String, Object> ret = new HashMap<String, Object>();
		if (ServletFileUpload.isMultipartContent(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> fileList = multipartRequest.getFiles(dstFileName);
			String ids="";
			for (MultipartFile item : fileList) {
				try {
					//插入文件存储表
					String id=sysDatasService.insertSelective(item);
					if (ids.equals("")){
						ids+=id;
					}else{
						ids+=","+id;
					}
					ret.put("success", true);
					ret.put("message", "上传成功!");
				} catch (Exception e) {
					ret.put("success", false);
					ret.put("message", e.getMessage());
				}
			}
			ret.put("ids", ids);
		}
		return ret;
	}
	/**
	 * 上传文件
	 */
	@PostMapping("/upload2")
	@ResponseBody
	public List<Map<String,String>> updateAvatar2(@RequestParam MultipartFile[] myfiles) throws IOException {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		for (MultipartFile myfile:myfiles){
			//插入文件存储表
			String id=sysDatasService.insertSelective(myfiles[0]);
			Map<String,String> map = new HashMap<String,String>();
			map.put("pathUrl","/FileController/viewImg/"+id);
			list.add(map);
		}
		return list;
	}

	/**
	 * 上传文件全路径（用户富文本上传）
	 */
	@PostMapping("/upload3")
	@ResponseBody
	public List<Map<String,String>> updateAvatar3(@RequestParam MultipartFile[] myfiles,HttpServletRequest request) throws IOException {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		String scheme = request.getScheme();//http
		String serverName = request.getServerName();//localhost
		/*InetAddress ia=InetAddress.getLocalHost();
		String ip=ia.getHostAddress();*/
		//String ip= CustomSystemUtil.getInternetIp();
		int serverPort = request.getServerPort();//8080
		for (MultipartFile myfile:myfiles){
			//插入文件存储表
			String id=sysDatasService.insertSelective(myfiles[0]);
			Map<String,String> map = new HashMap<String,String>();
			map.put("pathUrl",scheme+"://"+serverName+":"+serverPort+"/FileController/viewImg/"+id);
			list.add(map);
		}
		return list;
	}
    /**
     * 上传文件
     */
    @PostMapping("/upload")
	@ResponseBody
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file)
    {
        try
        {
            if (!file.isEmpty())
            {
                //插入文件存储表
				String id=sysDatasService.insertSelective(file);
                if(id!=null){
                	 return AjaxResult.successData(200, id);
                }
            }
            return error();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 文件添加
     * @param file
     * @return
     */
	@PostMapping("add")
	@RequiresPermissions("system:file:add")
	@ResponseBody
	public AjaxResult add(TsysFile file,String dataId){
		int b=sysFileService.insertSelective(file,dataId);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}

	/**
	 * 删除文件
	 * @param ids
	 * @return
	 */
	@PostMapping("remove")
	@RequiresPermissions("system:file:remove")
	@ResponseBody
	public AjaxResult remove(String ids){
		int b=sysFileService.deleteByPrimaryKey(ids);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}

	/**
	 * 检查文件名字
	 * @param tsysFile
	 * @return
	 */
	@PostMapping("checkNameUnique")
	@ResponseBody
	public int checkNameUnique(TsysFile tsysFile){
		int b=sysFileService.checkNameUnique(tsysFile);
		if(b>0){
			return 1;
		}else{
			return 0;
		}
	}


	/**
	 * 修改文件
	 * @param id
	 * @param mmap
	 * @return
	 */
	@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("tsysFile", sysFileService.selectByPrimaryKey(id));
        return prefix + "/edit";
    }

	/**
     * 修改保存文件
     */
    @RequiresPermissions("system:user:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TsysFile tsysFile,String dataId)
    {
        return toAjax(sysFileService.updateByPrimaryKey(tsysFile,dataId));
    }


    @GetMapping("/viewfile/{id}")
    public String viewfile(@PathVariable("id") String id,ModelMap mmap){
    	mmap.put("tsysDatas",sysFileDatasService.queryfileID(id));
        return prefix + "/viewfile";
    }

    @GetMapping("/viewImg/{id}")
    public void viewIMG(@PathVariable("id") String id,HttpServletRequest request,HttpServletResponse response){
    	TsysDatas datas= sysDatasService.selectByPrimaryKey(id);
    	/*try {
			FileUtils.readIMGTohtml(request, response, datas.getFilePath());
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		String filePath = datas.getFilePath();
		File imageFile = new File(filePath);
		if (imageFile.exists()) {
			FileInputStream fis = null;
			OutputStream os = null;
			try {
				fis = new FileInputStream(imageFile);
				os = response.getOutputStream();
				int count = 0;
				byte[] buffer = new byte[1024 * 8];
				while ((count = fis.read(buffer)) != -1) {
					os.write(buffer, 0, count);
					os.flush();
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fis.close();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
    }



}
